import { getMenu } from '@/api/systemManage'
import router, { resetRouter, lastRoutes } from '@/router'
import { validateNull } from './validate'

export function getMenuList (){
  return getMenu().then(res => {
    resetRouter()
    const dynamicRoutes = formatRoutes(res.value)
    console.log('dynamicRoutes', dynamicRoutes.concat(lastRoutes))
    router.addRoutes(lastRoutes)
    console.log('router', router)
  }).catch(err=> console.log(err))
}

// 处理动态路由
export function formatRoutes(menu) {
  const router = []
  menu.forEach(menuItem => {
    const {path, component, redirect, name, meta, children, hidden, alwaysShow} = menuItem
    if (!validateNull(component)) {
      const routerItem = {
        path,
        redirect,
        name,
        meta,
        hidden,
        alwaysShow,
        component: () => import(component),
        children: validateNull(children) ? [] : formatRoutes(children),
      }
      router.push(routerItem)
    }
  })
  return router
}